// The payment page
// ================

define(['zepto', 'utils', 'wxupload', 'wxshare', 'cityPicker'], function($, utils, wxupload, wxshare) {
  return {

    init: function(data) {
      
      // forbidden wx share
      wxshare.initShare(data.jsConfig, false)
      
      this.bindQrcodeUpload(data.jsConfig);
      
      this.bindCountrySelect();
      
      this.bindPCDSelect();
      
      this.bindPositionSelect();
      
      this.bindSalarySelect();

      this.bindSubmitAction();

    },

    bindQrcodeUpload : function(config) {

      var uploadButtin = $("a.upload-image"),
          that = this;
      $(document).on('click', '.checkbox,.radio', function(e){
        $(this).children("input").prop("checked", !$(this).children("input").prop("checked"));
      })
      
      wxupload.injectConfig(config)
      
      uploadButtin.on('click', function(e){
        
        wxupload.invokeUpload(

          function(localId) {
            $(".upload-image").text("已选择，可点击重新选择");
          },
          
          function(mediaId) {
            $('input[name="mediaId"]').val(mediaId);
          }
        )
        
      })

    },
    
    bindCountrySelect: function(sites) {
        
        that = this
        
        var $countrySelector = $("input[name='countrySelector']")
        
        $countrySelector.picker({
          toolbarTemplate: '<header class="bar bar-nav">\
                              <button class="button button-link pull-right close-picker">确定</button>\
                              <h1 class="title">请选择国家</h1>\
                           </header>',
          cols: [
            {
              textAlign: 'center',
              values: ['CHINA', 'OTHER'],
              displayValues: ['中国', '其他']
            }
          ],
          formatValue: function (picker, value, displayValue){
            $(this.input).next().val(displayValue)
            if(value == 'OTHER') {
              $(".pcd-select").addClass("hide");
            }else {
              $(".pcd-select").removeClass("hide");
            }
            return displayValue
          }
        });
        
      },
    
    bindPCDSelect: function() {
        
        that = this
        
        var $marriageSelector = $("input[name='pcdSelector']")
        
        $marriageSelector.cityPicker({
          toolbarTemplate: '<header class="bar bar-nav">\
                              <button class="button button-link pull-right close-picker">确定</button>\
                              <h1 class="title">请选择省市区</h1>\
                           </header>',
         formatValue: function (picker, value, displayValue){
             $(this.input).next().val(value)
             console.log(displayValue);
             if(displayValue[3] === "") {
               return displayValue[0] + displayValue[1];
               $(this.input)
             } else {
               return displayValue[0] + displayValue[1] + displayValue[2];
             }
           }
        });
    },
    
    bindPositionSelect: function() {
      var that = this
      var $positionSelector = $("input[name='position']")
      
      $positionSelector.picker({
	      toolbarTemplate: '<header class="bar bar-nav">\
	                          <button class="button button-link pull-right close-picker">确定</button>\
	                          <h1 class="title">请选择身份</h1>\
	                       </header>',
	      cols: [
	        {
	          textAlign: 'center',
	          values: ["学生", "妈妈", "白领", "自由职业", "企业主", "海外党"]
	        }
	      ]
	    });
    },
    
    bindSalarySelect: function() {
        var that = this
        var $salarySelector = $("input[name='salary']")
        
        $salarySelector.picker({
  	      toolbarTemplate: '<header class="bar bar-nav">\
  	                          <button class="button button-link pull-right close-picker">确定</button>\
  	                          <h1 class="title">请选择薪资</h1>\
  	                       </header>',
  	      cols: [
  	        {
  	          textAlign: 'center',
  	          values: ["5000以下", "5000-10000", "10000-20000", "20000以上"]
  	        }
  	      ]
  	    });
      },

    // order submit evvent handler
    bindSubmitAction: function() {
      
      var thatSubmit = this
      
      var submitButton = $("a.button-submit")
      
      submitButton.on('click', function(e){
        e.preventDefault()
        // init all data
        var data = thatSubmit.onInitData()
        // validate all input
        if(thatSubmit.onValidateData(data)) {
          // do submit order with data
          data = thatSubmit.onAppendData(data)
          thatSubmit.onSubmitOrder(data)
        }
      })
      
    },

    // init data
    onInitData: function() {
      return {
        '_method': {
          'value': $('input[name="_method"]').val().trim(),
          'message': '提交方式不能为空'
        },
        'wechatCode': {
          'value': $('input[name="wechatCode"]').val().trim(),   
          'message': '手机号不能为空'
        },
        'mailbox': {
            'value': $('input[name="mailbox"]').val().trim(),
            'message': '请填写邮箱'
        },
        'country': {
            'value': $('input[name="country"]').val().trim(),   
            'message': '国家不能为空'
        },
        'address': {
          'value': $('textarea[name="address"]').val().trim(),   
          'message': '邮寄地址不能为空'
        },
        'position': {
          'value': $('input[name="position"]').val().trim(),   
          'message': '你的身份不能为空'
        },
        'salary': {
            'value': $('input[name="salary"]').val().trim(),   
            'message': '你的薪资不能为空'
          }
      }
    },

    onValidateData: function(data) {
      var valid = _.find(data, function(item) {
        return !item.value
      })

      if (!!valid) return $.toast(valid.message)
      
      var mailbox = data.mailbox.value;
      var emailRe = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
      if(!emailRe.test(mailbox)) {
        $.toast("请输入正确的邮箱格式")
        return false
      }
      
      var $wechatCode = $("input[name=wechatCode]")
      var patrn = "/^[a-zA-Z]+[a-zA-Z\d_-]{5,19}$/";
      // if(!/^[a-zA-Z]+[a-zA-Z\d_-]{5,19}$/.test($wechatCode.val().trim())) {
    	//   return $.toast('请输入以字母开头的微信号')
      // }
      
      var country = $('input[name="country"]').val()
      
      if(country == '中国') {
        var pcd = $('input[name="pcd"]').val();
        if(!pcd) {
          $.toast("请选择省市区")
          return false;
        }else {
          var pcds = pcd.split(",");
          $("input[name='province']").val(pcds[0])
          $("input[name='region']").val(pcds[2] == '' ? pcds[0] : pcds[2])
          $("input[name='district']").val(pcds[2] == '' ? pcds[1] : pcds[2])
        }
      }else {
        $("input[name='province']").val("");
        $("input[name='region']").val("");
        $("input[name='district']").val("");
      }
      
      data.province = {"value": $("input[name='province']").val()};
      data.district = {"value": $("input[name='district']").val()};
      data.region = {"value": $("input[name='region']").val()};
      
      // var historyQrcodePath = $("input[name='historyQrcodePath']").val()
      
      // if(!historyQrcodePath) {
      //   var mediaId = $("input[name='mediaId']").val();
      //   if(!mediaId) {
      //     $.toast("请上传微信二维码")
      //     return false;
      //   }
      // }
      
      return true
    },

    onAppendData: function(data) {
            
      var pcd = $("input[name='pcd']").val();
      var country = $('input[name="country"]').val();
      
      if(pcd && country == '中国') {
        data.pcd = {
         'value': pcd
        }
      }
      
      var mediaId = $("input[name='mediaId']").val();
      
      if(mediaId) {
        data.mediaId = {
          'value': mediaId
        }
      }
      
      var remarks = $("textarea[name='remarks']").val();
      
      if(remarks) {
        data.remarks = {
          'value': remarks
        }
      }
      
      return data;
    },

    onSubmitOrder: function(data) {

      $.showPreloader('正在提交')

      var processedData = _.mapObject(data, function(obj) {
        return obj.value
      })
      $.ajax({
        type: 'POST',
        url: __CTX__.root + '/investigations/profile',
        data: processedData
      }).done(function(response) {
        $.hidePreloader()
        utils.processResult(response, function(result) {
          $.toast('填写个人信息成功')
          setTimeout(function() {
            window.location.href = __CTX__.root + '/investigations'
          }, 1000)
        }, function(result) {
          $.toast(result.message || '填写个人信息失败')
        })
      })
      
    }
  }
})